package cn.chiship.framework.upms.biz.system.service.impl;

import cn.chiship.framework.upms.biz.system.entity.UpmsNoticeExample;
import cn.chiship.framework.upms.biz.system.entity.UpmsNoticeSend;
import cn.chiship.framework.upms.biz.system.entity.UpmsNoticeSendExample;
import cn.chiship.framework.upms.biz.system.mapper.UpmsNoticeSendMapper;
import cn.chiship.framework.upms.biz.system.service.UpmsNoticeService;
import cn.chiship.framework.upms.biz.user.entity.UpmsUser;
import cn.chiship.framework.upms.biz.user.entity.UpmsUserExample;
import cn.chiship.framework.upms.biz.user.mapper.UpmsUserMapper;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.upms.biz.system.entity.UpmsNotice;
import cn.chiship.framework.upms.biz.system.mapper.UpmsNoticeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 通知公告表业务接口实现层
 * 2021/10/22
 *
 * @author lijian
 */
@Service
public class UpmsNoticeServiceImpl extends BaseServiceImpl<UpmsNotice, UpmsNoticeExample> implements UpmsNoticeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsNoticeServiceImpl.class);
    private static final String SEND_SCOPE_ALL = "ALL";
    private static final String SEND_SCOPE_USER = "USER";
    private static final Byte SEND_STATUS_REVOKE = 2;

    @Resource
    UpmsNoticeMapper upmsNoticeMapper;
    @Resource
    UpmsNoticeSendMapper upmsNoticeSendMapper;
    @Resource
    UpmsUserMapper upmsUserMapper;

    @Override
    public BaseResult insertSelective(UpmsNotice upmsNotice) {
        upmsNotice.setStartTime(System.currentTimeMillis());
        upmsNotice.setSendTime(System.currentTimeMillis());
        upmsNotice.setSendStatus(Byte.valueOf("0"));
        return super.insertSelective(upmsNotice);
    }

    @Override
    public UpmsNotice selectByPrimaryKey(Object id) {
        UpmsNoticeExample noticeExample = new UpmsNoticeExample();
        noticeExample.createCriteria().andIdEqualTo(id.toString());
        List<UpmsNotice> notices = upmsNoticeMapper.selectByExampleWithBLOBs(noticeExample);
        if (notices.isEmpty()) {
            return null;
        }
        return notices.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult deleteByExample(UpmsNoticeExample upmsNoticeExample) {

        List<String> noticeIds = new ArrayList<>();
        List<UpmsNotice> upmsNotices = upmsNoticeMapper.selectByExample(upmsNoticeExample);
        for (UpmsNotice notice : upmsNotices) {
            noticeIds.add(notice.getId());
        }
        if (!noticeIds.isEmpty()) {
            UpmsNoticeSendExample upmsNoticeSendExample = new UpmsNoticeSendExample();
            upmsNoticeSendExample.createCriteria().andNoticeIdIn(noticeIds);
            upmsNoticeSendMapper.deleteByExample(upmsNoticeSendExample);
        }
        super.deleteByExample(upmsNoticeExample);
        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult changeSendStatus(Object id, Byte sendStatus) {
        /**
         * 1  恢复
         *      1.新增所有接收者
         *          1.全体用户   查找用户列表 挨个添加
         *          2.指定用户  循环添加
         *      2.更改状态、撤销时间置空
         * 2  撤销
         *      1.删除所有接收者
         *      2.更改状态、填充撤销时间
         */
        UpmsNotice notice = upmsNoticeMapper.selectByPrimaryKey(id);
        notice.setSendStatus(sendStatus);
        if (1 == sendStatus) {
            notice.setCancelTime(null);
            List<String> userIds = new ArrayList<>();
            if (SEND_SCOPE_ALL.equals(notice.getNoticeCategory())) {
                UpmsUserExample upmsUserExample = new UpmsUserExample();
                upmsUserExample.createCriteria().andIsLockedEqualTo(BaseConstants.NO).andIsDeletedEqualTo(BaseConstants.NO);
                List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
                for (UpmsUser user : users) {
                    userIds.add(user.getId());
                }
            }
            if (SEND_SCOPE_USER.equals(notice.getNoticeCategory())) {
                if (!StringUtil.isNullOrEmpty(notice.getReceiver())) {
                    Arrays.asList(notice.getReceiver().split(";")).forEach(item -> {
                        userIds.add(item.split(":")[0]);
                    });
                }
            }
            if (!userIds.isEmpty()) {
                for (String userId : userIds) {
                    UpmsNoticeSend upmsNoticeSend = new UpmsNoticeSend();
                    upmsNoticeSend.setId(SnowflakeIdUtil.generateStrId());
                    upmsNoticeSend.setGmtCreated(System.currentTimeMillis());
                    upmsNoticeSend.setGmtModified(System.currentTimeMillis());
                    upmsNoticeSend.setIsDeleted(BaseConstants.NO);
                    upmsNoticeSend.setNoticeId(notice.getId());
                    upmsNoticeSend.setUserId(userId);
                    upmsNoticeSend.setReadFlag(Byte.valueOf("0"));
                    upmsNoticeSend.setNoticeType(notice.getNoticeType());
                    upmsNoticeSendMapper.insertSelective(upmsNoticeSend);
                }
            }
        }
        if (SEND_STATUS_REVOKE.equals(sendStatus)) {
            notice.setCancelTime(System.currentTimeMillis());
            UpmsNoticeSendExample upmsNoticeSendExample = new UpmsNoticeSendExample();
            upmsNoticeSendExample.createCriteria().andNoticeIdEqualTo(notice.getId());
            upmsNoticeSendMapper.deleteByExample(upmsNoticeSendExample);
        }
        super.updateByPrimaryKeySelective(notice);
        return BaseResult.ok();
    }
}
